export default function ObjectToHtml(data) {
    // 若传入数值为json，则转换为字符串
    let txt = typeof data === 'string' ? data : JSON.stringify(data);
    // 转换为Object
    let obj;
    try {
        obj = JSON.parse(txt);
    } catch (e) {
        return '数据源语法错误,JSON格式化失败! 错误信息: ' + e.description;
    }
    let line = '</br>', // 换行
        indentChar = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; // 缩进量
    // 判断是否为对象
    let isObject = function (item) {
        return item && typeof item === 'object' && Object.prototype.toString.call(item) !== '[object Array]';
    };
    let getTab = function (num) {
        let tab = '';
        for (let i = 0; i < num; i++) {
            tab += indentChar;
        }
        return tab;
    };
    // 检测递归
    let format = function (value, indent, isLast, inArray) {
        let str = '';
        // [
        //   value,
        //   value
        // ]，并将进入检测递归
        if (Object.prototype.toString.call(value) === '[object Array]') {
            str += '[' + (isObject(value[0]) ? '' : (line + getTab(++indent)));
            value.forEach(function (item, index) {
                str += format(item, indent, index === (value.length - 1), true);
                // 若不为对象，则进行换行
                str += isObject(item) ? '' : (line + getTab((index === (value.length - 1)) ? --indent : indent));
            });
            str += ']';
            // null，将处理为`<span class="null">null</span>`
        } else if (value === null) {
            str += '<span class="null">null</span>';
            // 对象Object，将处理为`{<span class="key">"key"</span>:value}`，并进入检测递归
        } else if (typeof value === 'object') {
            str += '{' + line + getTab(++indent);
            var keys = Object.keys(value);
            keys.forEach(function (key, index) {
                str += '<span class="key">"' + key + '"</span>: ' + format(value[key], indent, index === (keys.length - 1));
            });
            str += '}';
            indent--;
            // true/false，将处理为`<span class="boolen/null">true/false</span>`
        } else if (typeof value === 'boolean') {
            str += '<span class="boolean">' + value + '</span>';
            // 字符串，将处理为`<span class="string">"string"</span>`
        } else if (typeof value === 'string') {
            str += '<span class="string">"' + value + '"</span>';
            // 数字Number，将处理为`<span class="number">1</span>`
        } else {
            str += '<span class="number">' + value + '</span>';
        }
        str += (isLast ? '' : ',') + (inArray ? '' : (line + getTab(isLast ? --indent : indent)));
        return str;
    }
    return ('<div class="json">' + format(obj, 0, true) + '</div>');
}
